package com.xiongtian.springframework.beans.factory.support;

import com.xiongtian.springframework.beans.BeansException;
import com.xiongtian.springframework.beans.factory.FactoryBean;
import com.xiongtian.springframework.beans.factory.config.BeanDefinition;
import com.xiongtian.springframework.beans.factory.config.BeanPostProcessor;
import com.xiongtian.springframework.beans.factory.config.ConfigurableBeanFactory;
import com.xiongtian.springframework.util.ClassUtils;
import com.xiongtian.springframework.util.StringValueResolver;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: xiongtian
 * @CreateTime: 2025-03-25  10:27
 * @Version: 1.0
 * @Description: 抽象Bean工厂类
 * 实现BeanFactory.getBean(String beanName)
 * 定义创建bean的抽象方法
 * 定义获取BeanDefinition的抽象方法
 */

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {


    /**
     * ClassLoader to resolve bean class names with, if necessary
     */
    private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();

    /**
     * BeanPostProcessors to apply in createBean
     */
    private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<BeanPostProcessor>();

    /**
     * String resolvers to apply e.g. to annotation attribute values
     */
    private final List<StringValueResolver> embeddedValueResolvers = new ArrayList<>();

    /**
     * 获取Bean
     *
     * @param beanName Bean名称
     * @return Bean对象
     */
    @Override
    public Object getBean(String beanName) throws BeansException {
        return doGetBean(beanName, null);
    }

    /**
     * 获取Bean
     * 支持Bean构造函数参数
     *
     * @param beanName Bean名称
     * @param args     Bean构造函数参数
     * @return
     * @throws BeansException
     */
    @Override
    public Object getBean(String beanName, Object... args) throws BeansException {
        return doGetBean(beanName, args);
    }


    /**
     * 获取Bean
     * 支持Bean类型
     *
     * @param name         Bean名称
     * @param requiredType Bean类型
     * @param <T>          Bean类型
     * @return Bean对象
     * @throws BeansException 异常
     */
    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return (T) getBean(name);
    }


    /**
     * 获取Bean
     *
     * @param beanName Bean名称
     * @param args     Bean构造函数参数
     * @param <T>      Bean类型
     * @return Bean对象
     */
    protected <T> T doGetBean(final String beanName, final Object[] args) {
        Object shareInstance = getSingleton(beanName);

        if (null != shareInstance) {
            //  如果是 FactoryBean，调用 getObject() 方法
            return (T) getObjectForBeanInstance(shareInstance, beanName);
        }

        BeanDefinition beanDefinition = getBeanDefinition(beanName);
        Object bean = createBean(beanName, beanDefinition, args);
        return (T) getObjectForBeanInstance(bean, beanName);
    }


    /**
     * 根据bean的种类返回实例
     * 如果是 FactoryBean，调用 getObject() 方法
     * 1.不是FactoryBean，直接返回
     * 2.尝试从缓存中获取
     * 3.缓存没有，从FactoryBean中获取
     *
     * @param beanInstance bean实例
     * @param beanName     bean名称
     * @return bean实例
     */
    private Object getObjectForBeanInstance(Object beanInstance, String beanName) {
        if (!(beanInstance instanceof FactoryBean)) {
            return beanInstance;
        }
        Object object = getCachedObjectForFactoryBean(beanName);
        if (null == object) {
            FactoryBean<?> factoryBean = (FactoryBean<?>) beanInstance;
            object = getObjectFromFactoryBean(factoryBean, beanName);
        }
        return object;
    }

    /**
     * 添加BeanPostProcessor
     *
     * @param beanPostProcessor bean后置处理器
     */
    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        this.beanPostProcessors.remove(beanPostProcessor);
        this.beanPostProcessors.add(beanPostProcessor);
    }

    /**
     * 创建Bean
     * 抽象方法，由子类实现
     *
     * @param beanName       Bean名称
     * @param beanDefinition Bean定义
     * @param args           Bean构造函数参数
     * @return Bean对象
     */
    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException;

    /**
     * 获取Bean定义
     *
     * @param beanName Bean名称
     * @return Bean定义
     */
    protected abstract BeanDefinition getBeanDefinition(String beanName);

    /**
     * Return the list of BeanPostProcessors that will get applied
     * to beans created with this factory.
     */
    public List<BeanPostProcessor> getBeanPostProcessors() {
        return this.beanPostProcessors;
    }


    /**
     * Return the ClassLoader that should be used to load bean
     * classes.
     * <p>Default is the {@linkplain ClassUtils#getDefaultClassLoader() default ClassLoader}.
     *
     * @return the ClassLoader (only {@code null} if even the system
     * ClassLoader isn't accessible)
     */
    public ClassLoader getBeanClassLoader() {
        return this.beanClassLoader;
    }


    @Override
    public void addEmbeddedValueResolver(StringValueResolver valueResolver) {
        this.embeddedValueResolvers.add(valueResolver);
    }

    @Override
    public String resolveEmbeddedValue(String value) {
        String result = value;
        for (StringValueResolver resolver : this.embeddedValueResolvers) {
            result = resolver.resolveStringValue(result);
        }
        return result;
    }

}
